package com.example.memo2.ui.detail

import android.Manifest
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.widget.ArrayAdapter
import androidx.activity.OnBackPressedCallback
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.memo2.R
import com.example.memo2.data.model.Memo
import com.example.memo2.data.model.Priority
import com.example.memo2.databinding.ActivityMemoDetailBinding
import com.example.memo2.notification.ReminderManager
import com.example.memo2.ui.MemoViewModel
import com.example.memo2.utils.AudioManager
import com.example.memo2.utils.MediaUtils
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class MemoDetailActivity : AppCompatActivity(), AudioManager.AudioCallback {
    
    private lateinit var binding: ActivityMemoDetailBinding
    private val viewModel: MemoViewModel by viewModels()
    private lateinit var reminderManager: ReminderManager
    private lateinit var audioManager: AudioManager
    private lateinit var imageAdapter: ImagePreviewAdapter
    
    private var currentMemo: Memo? = null
    private var isEditMode = false
    private var selectedReminderTime: Date? = null
    private var currentImagePaths = mutableListOf<String>()
    private var currentAudioPath: String? = null
    private var tempPhotoUri: Uri? = null
    
    // 权限请求
    private val notificationPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (!isGranted) {
            Snackbar.make(binding.root, getString(R.string.notification_permission_required), Snackbar.LENGTH_LONG).show()
        }
    }
    
    private val cameraPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            openCamera()
        } else {
            Snackbar.make(binding.root, getString(R.string.camera_permission_required), Snackbar.LENGTH_LONG).show()
        }
    }
    
    private val audioPermissionLauncher = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { isGranted ->
        if (isGranted) {
            toggleRecording()
        } else {
            Snackbar.make(binding.root, getString(R.string.audio_permission_required), Snackbar.LENGTH_LONG).show()
        }
    }
    
    // 图片选择
    private val imagePickerLauncher = registerForActivityResult(
        ActivityResultContracts.GetContent()
    ) { uri ->
        uri?.let { addImageFromUri(it) }
    }
    
    // 拍照
    private val cameraLauncher = registerForActivityResult(
        ActivityResultContracts.TakePicture()
    ) { success ->
        if (success && tempPhotoUri != null) {
            addImageFromUri(tempPhotoUri!!)
        }
    }
    
    companion object {
        const val EXTRA_MEMO_ID = "memo_id"
        const val EXTRA_IS_NEW = "is_new"
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMemoDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        reminderManager = ReminderManager(this)
        audioManager = AudioManager(this)
        audioManager.setAudioCallback(this)
        
        setupImageRecyclerView()
        setupBackPressedHandler()
        setupPrioritySpinner()
        setupListeners()
        checkNotificationPermission()
        
        val memoId = intent.getLongExtra(EXTRA_MEMO_ID, -1L)
        isEditMode = intent.getBooleanExtra(EXTRA_IS_NEW, false)
        
        if (memoId != -1L) {
            loadMemo(memoId)
        } else {
            // 新建备忘录
            isEditMode = true
            enableEditMode()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        audioManager.release()
    }
    
    private fun setupImageRecyclerView() {
        imageAdapter = ImagePreviewAdapter { imagePath ->
            removeImage(imagePath)
        }
        
        binding.imagesRecyclerView.apply {
            adapter = imageAdapter
            layoutManager = LinearLayoutManager(this@MemoDetailActivity, LinearLayoutManager.HORIZONTAL, false)
        }
    }
    
    private fun setupBackPressedHandler() {
        onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                if (isEditMode && currentMemo == null) {
                    // 如果是新建备忘录且在编辑状态，直接退出
                    finish()
                } else if (isEditMode) {
                    // 如果在编辑已有备忘录，切换到查看模式
                    isEditMode = false
                    disableEditMode()
                } else {
                    // 否则正常退出
                    finish()
                }
            }
        })
    }
    
    private fun setupPrioritySpinner() {
        val priorities = Priority.entries.map { getString(it.displayNameResId) }
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, priorities)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spinnerPriority.adapter = adapter
    }
    
    private fun setupListeners() {
        binding.buttonSetReminder.setOnClickListener {
            showDateTimePicker()
        }
        
        binding.buttonClearReminder.setOnClickListener {
            selectedReminderTime = null
            updateReminderDisplay()
        }
        
        binding.fabEdit.setOnClickListener {
            isEditMode = true
            enableEditMode()
        }
        
        binding.fabSave.setOnClickListener {
            saveMemo()
        }
        
        // 多媒体按钮
        binding.buttonAddImage.setOnClickListener {
            imagePickerLauncher.launch("image/*")
        }
        
        binding.buttonTakePhoto.setOnClickListener {
            checkCameraPermissionAndTakePhoto()
        }
        
        binding.buttonRecord.setOnClickListener {
            checkAudioPermissionAndRecord()
        }
        
        // 音频控制
        binding.buttonPlayPause.setOnClickListener {
            currentAudioPath?.let { audioPath ->
                if (audioManager.isPlaying()) {
                    audioManager.pausePlayback()
                } else {
                    audioManager.playAudio(audioPath)
                }
            }
        }
        
        binding.buttonDeleteAudio.setOnClickListener {
            deleteAudio()
        }
        
        // 添加删除备忘录按钮事件
        binding.fabDelete.setOnClickListener {
            showDeleteConfirmDialog()
        }
    }
    
    private fun enableEditMode() {
        binding.editTitle.isEnabled = true
        binding.editContent.isEnabled = true
        binding.spinnerPriority.isEnabled = true
        binding.buttonSetReminder.isEnabled = true
        binding.buttonClearReminder.isEnabled = true
        binding.buttonAddImage.isEnabled = true
        binding.buttonTakePhoto.isEnabled = true
        binding.buttonRecord.isEnabled = true
        
        // 更新FAB显示
        binding.fabEdit.hide()
        binding.fabSave.show()
        binding.fabDelete.hide() // 编辑模式下隐藏删除按钮
        
        // 请求焦点到标题
        binding.editTitle.requestFocus()
    }
    
    private fun disableEditMode() {
        binding.editTitle.isEnabled = false
        binding.editContent.isEnabled = false
        binding.spinnerPriority.isEnabled = false
        binding.buttonSetReminder.isEnabled = false
        binding.buttonClearReminder.isEnabled = false
        binding.buttonAddImage.isEnabled = false
        binding.buttonTakePhoto.isEnabled = false
        binding.buttonRecord.isEnabled = false
        
        // 更新FAB显示
        binding.fabSave.hide()
        binding.fabEdit.show()
        // 只有在查看已存在备忘录时才显示删除按钮
        if (currentMemo != null) {
            binding.fabDelete.show()
        }
    }
    
    private fun loadMemo(memoId: Long) {
        lifecycleScope.launch {
            currentMemo = viewModel.getMemoById(memoId)
            currentMemo?.let { memo ->
                binding.editTitle.setText(memo.title)
                binding.editContent.setText(memo.content)
                binding.spinnerPriority.setSelection(memo.priority.value)
                selectedReminderTime = memo.reminderTime
                updateReminderDisplay()
                
                // 加载图片
                currentImagePaths.clear()
                currentImagePaths.addAll(MediaUtils.parseImagePaths(memo.imagePaths))
                updateImageDisplay()
                
                // 加载音频
                currentAudioPath = memo.audioPath
                updateAudioDisplay()
            }
        }
    }
    
    private fun updateImageDisplay() {
        if (currentImagePaths.isNotEmpty()) {
            binding.imagesRecyclerView.visibility = android.view.View.VISIBLE
            imageAdapter.submitList(currentImagePaths.toList())
            // 添加调试日志
            println("更新图片显示，数量: ${currentImagePaths.size}")
        } else {
            binding.imagesRecyclerView.visibility = android.view.View.GONE
        }
    }
    
    private fun updateAudioDisplay() {
        if (currentAudioPath != null) {
            binding.audioControlLayout.visibility = android.view.View.VISIBLE
            binding.audioFileName.text = MediaUtils.getFileName(currentAudioPath!!)
            val duration = MediaUtils.getAudioDuration(currentAudioPath!!)
            binding.audioDuration.text = MediaUtils.formatDuration(duration)
            binding.buttonPlayPause.setImageResource(R.drawable.ic_play)
        } else {
            binding.audioControlLayout.visibility = android.view.View.GONE
        }
    }
    
    private fun addImageFromUri(uri: Uri) {
        val imagePath = MediaUtils.copyImageFromUri(this, uri)
        if (imagePath != null) {
            currentImagePaths.add(imagePath)
            updateImageDisplay()
            // 添加调试日志
            println("图片已添加: $imagePath")
            println("当前图片列表: $currentImagePaths")
        } else {
            Snackbar.make(binding.root, getString(R.string.image_add_failed), Snackbar.LENGTH_SHORT).show()
        }
    }
    
    private fun removeImage(imagePath: String) {
        currentImagePaths.remove(imagePath)
        MediaUtils.deleteFile(imagePath)
        updateImageDisplay()
    }
    
    private fun checkCameraPermissionAndTakePhoto() {
        when {
            ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED -> {
                openCamera()
            }
            else -> {
                cameraPermissionLauncher.launch(Manifest.permission.CAMERA)
            }
        }
    }
    
    private fun openCamera() {
        val photoFile = File(MediaUtils.getImagesDir(this), "temp_photo_${System.currentTimeMillis()}.jpg")
        tempPhotoUri = FileProvider.getUriForFile(this, "${packageName}.fileprovider", photoFile)
        cameraLauncher.launch(tempPhotoUri)
    }
    
    private fun checkAudioPermissionAndRecord() {
        when {
            ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED -> {
                toggleRecording()
            }
            else -> {
                audioPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
            }
        }
    }
    
    private fun toggleRecording() {
        if (audioManager.isRecording()) {
            audioManager.stopRecording()
            binding.buttonRecord.text = getString(R.string.recording_start)
        } else {
            audioManager.startRecording()
            binding.buttonRecord.text = getString(R.string.recording_stop)
        }
    }
    
    private fun deleteAudio() {
        currentAudioPath?.let { path ->
            MediaUtils.deleteFile(path)
            currentAudioPath = null
            updateAudioDisplay()
        }
    }
    
    // AudioManager.AudioCallback 实现
    override fun onRecordingStarted() {
        runOnUiThread {
            binding.buttonRecord.text = getString(R.string.recording_stop)
        }
    }
    
    override fun onRecordingStopped(filePath: String) {
        runOnUiThread {
            binding.buttonRecord.text = getString(R.string.recording_start)
            currentAudioPath = filePath
            updateAudioDisplay()
        }
    }
    
    override fun onRecordingError(error: String) {
        runOnUiThread {
            binding.buttonRecord.text = getString(R.string.recording_start)
            Snackbar.make(binding.root, error, Snackbar.LENGTH_LONG).show()
        }
    }
    
    override fun onPlaybackStarted() {
        runOnUiThread {
            binding.buttonPlayPause.setImageResource(R.drawable.ic_pause)
        }
    }
    
    override fun onPlaybackCompleted() {
        runOnUiThread {
            binding.buttonPlayPause.setImageResource(R.drawable.ic_play)
        }
    }
    
    override fun onPlaybackError(error: String) {
        runOnUiThread {
            binding.buttonPlayPause.setImageResource(R.drawable.ic_play)
            Snackbar.make(binding.root, error, Snackbar.LENGTH_LONG).show()
        }
    }
    
    private fun checkNotificationPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.POST_NOTIFICATIONS
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                notificationPermissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    }
    
    private fun showDateTimePicker() {
        val calendar = Calendar.getInstance()
        
        DatePickerDialog(
            this,
            { _, year, month, dayOfMonth ->
                calendar.set(year, month, dayOfMonth)
                
                TimePickerDialog(
                    this,
                    { _, hourOfDay, minute ->
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)
                        calendar.set(Calendar.MINUTE, minute)
                        selectedReminderTime = calendar.time
                        updateReminderDisplay()
                    },
                    calendar.get(Calendar.HOUR_OF_DAY),
                    calendar.get(Calendar.MINUTE),
                    true
                ).show()
            },
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)
        ).show()
    }
    
    private fun updateReminderDisplay() {
        if (selectedReminderTime != null) {
            val formatter = SimpleDateFormat(getString(R.string.date_format), Locale.getDefault())
            binding.textReminderTime.text = formatter.format(selectedReminderTime!!)
            binding.textReminderTime.visibility = android.view.View.VISIBLE
            binding.buttonClearReminder.visibility = android.view.View.VISIBLE
        } else {
            binding.textReminderTime.visibility = android.view.View.GONE
            binding.buttonClearReminder.visibility = android.view.View.GONE
        }
    }
    
    private fun saveMemo() {
        val title = binding.editTitle.text.toString().trim()
        val content = binding.editContent.text.toString().trim()
        
        if (title.isEmpty()) {
            Snackbar.make(binding.root, getString(R.string.title_required), Snackbar.LENGTH_SHORT).show()
            return
        }
        
        val priority = Priority.entries[binding.spinnerPriority.selectedItemPosition]
        
        val memo = if (currentMemo != null) {
            currentMemo!!.copy(
                title = title,
                content = content,
                priority = priority,
                reminderTime = selectedReminderTime,
                imagePaths = MediaUtils.joinImagePaths(currentImagePaths),
                audioPath = currentAudioPath,
                updatedAt = Date()
            )
        } else {
            Memo(
                title = title,
                content = content,
                priority = priority,
                reminderTime = selectedReminderTime,
                imagePaths = MediaUtils.joinImagePaths(currentImagePaths),
                audioPath = currentAudioPath
            )
        }
        
        lifecycleScope.launch {
            if (currentMemo != null) {
                // 更新备忘录
                viewModel.updateMemo(memo)
                // 更新提醒
                reminderManager.updateReminder(memo)
            } else {
                // 插入新备忘录
                val memoId = viewModel.insertMemo(memo)
                // 设置提醒（需要有有效的ID）
                if (selectedReminderTime != null) {
                    val savedMemo = memo.copy(id = memoId)
                    reminderManager.setReminder(savedMemo)
                }
                currentMemo = memo.copy(id = memoId)
            }
        }
        
        Snackbar.make(binding.root, getString(R.string.memo_saved), Snackbar.LENGTH_SHORT).show()
        
        // 保存后切换到查看模式
        isEditMode = false
        disableEditMode()
    }
    
    private fun showDeleteConfirmDialog() {
        currentMemo?.let { memo ->
            androidx.appcompat.app.AlertDialog.Builder(this)
                .setTitle(getString(R.string.delete_confirm_title))
                .setMessage(getString(R.string.delete_confirm_message))
                .setPositiveButton(getString(R.string.action_confirm)) { _, _ ->
                    deleteMemoAndFinish(memo)
                }
                .setNegativeButton(getString(R.string.action_cancel), null)
                .show()
        }
    }
    
    private fun deleteMemoAndFinish(memo: Memo) {
        lifecycleScope.launch {
            viewModel.deleteMemo(memo)
            // 删除相关的媒体文件
            MediaUtils.parseImagePaths(memo.imagePaths).forEach { imagePath ->
                MediaUtils.deleteFile(imagePath)
            }
            memo.audioPath?.let { audioPath ->
                MediaUtils.deleteFile(audioPath)
            }
            
            Snackbar.make(binding.root, getString(R.string.memo_deleted), Snackbar.LENGTH_SHORT).show()
            finish()
        }
    }
} 